<template>
  <div class="app">
    <el-container>
      <el-aside :width="width" class="bg-aside">
        <Menu @collapse="collapse"></Menu>
      </el-aside>
      <el-main>
        <div class="main-header">
          <div class="main-bread">
            <Bread></Bread>
          </div>
          <div class="main-user">
            <el-dropdown>
              <span class="color-box el-dropdown-link" :style="{ background: actColor }"></span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="command(item)" v-for="item in colors" :key="item.color"><span
                      class="color-box" :style="{ background: item.color }"></span>{{ item.desc }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <div class="user-time">
              <el-tag type="primary"><Time></Time></el-tag>
            </div>
            <div class="user-username">
              <el-dropdown>
                <span class="el-dropdown-link">
                  {{ indexStore.userInfo.username }}
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="data.dialogShow = true">修改密码</el-dropdown-item>
                    <el-dropdown-item @click="loginOut">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
        <div class="router-box">
          <RouterView />
          <!-- <router-view v-slot="{ Component }">
            <keep-alive include="productList">
              <component :is="Component" />
            </keep-alive>
          </router-view> -->
        </div>
      </el-main>
    </el-container>

    <!-- 修改密码 -->
    <el-dialog v-model="data.dialogShow" title="修改密码" :close-on-click-modal="false" :close-on-press-escape="false"
      :show-close="false" top="12vh">
      <template #header>
        <p class="box-title textCenter" :class="indexStore.userInfo.first_login && indexStore.userInfo.is_general_agent ? 'mustPass' : ''">
          {{ indexStore.userInfo.first_login && indexStore.userInfo.is_general_agent ? '首次登录后台需修改登录密码和绑定谷歌验证！' : '修改密码' }}
        </p>
      </template>
      <el-form :model="data.query" :rules="data.rules" ref="addQuery" status-icon :validate-on-rule-change="false"
        :scroll-to-error="true">
        <form-item title="账号">
          <el-input clearable placeholder="请输入" autocomplete="off" disabled maxlength="20" v-model="indexStore.userInfo.username" />
        </form-item>
        <form-item title="旧密码" :pass="true" value="old_password">
          <el-input clearable placeholder="请输入" autocomplete="new-password" type="text"
            v-model="data.query.old_password" />
        </form-item>
        <form-item title="新密码" :pass="true" value="new_password">
          <el-input clearable placeholder="请输入" autocomplete="new-password" type="text"
            v-model="data.query.new_password" />
        </form-item>
        <form-item title="是否验证谷歌验证码" value="google_check">
          <el-radio-group v-model="data.query.google_check" size="large"
            @change="chooseGoogle">
            <el-radio-button label="不验证" :value="0" />
            <el-radio-button label="验证" :value="1" />
          </el-radio-group>
          <span class="tipsText">(开启谷歌验证后，登录后台需输入谷歌验证码；首次开启此功能需进行绑定“身份验证器”)</span>
        </form-item>
        <form-item title="谷歌Url" value="google_url" v-show="data.query.google_check" style="height:auto">
          <QrcodeVue :value="data.query.google_url" :size="140" fg-color="#000" />
          <el-input class="imWidth100 marginT5" v-model="data.query.google_url" type="text" readonly />
          <span class="tipsText">(该账号绑定的谷歌Url，自动生成)</span>
        </form-item>
        <form-item title="谷歌秘钥" value="google_secret" v-show="data.query.google_check">
          <el-input class="marginT5" v-model="data.query.google_secret" type="text" readonly />
          <span class="tipsText">(该账号绑定的谷歌秘钥，自动生成)</span>
        </form-item>
        <form-item title="谷歌验证码" :pass="indexStore.userInfo.google_check && indexStore.userInfo.google_url || data.query.google_check?true:false"
          value="google_code" v-show="data.query.google_check || indexStore.userInfo.google_url && indexStore.userInfo.google_check">
          <el-input class="marginT5" v-model="data.query.google_code" type="text" placeholder="请输入谷歌验证码" />
          <el-button class="marginL10" v-show="indexStore.userInfo.google_url && data.query.google_check?true:false"  type="warning" :disabled="data.query.google_code?false:true" @click="changeGoogle">更换谷歌绑定</el-button>
          <span class="tipsText">(该账号绑定的谷歌验证码)</span>
        </form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.dialogShow = false" v-if="indexStore.userInfo.is_general_agent && !indexStore.userInfo.first_login || !indexStore.userInfo.is_general_agent">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { RouterView, useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'
import QrcodeVue from 'qrcode.vue'

import Menu from '@/components/menu/menu.vue'
import Time from '@/components/time/time.vue'
import Bread from '@/components/bread/bread.vue'
import { getLang } from '@/utils/localstorage'
import { putchangePassword } from '@/api/user'
import { googleKey,checkGoogleKey } from '@/api/merchant'
import { theme, colors } from '@/theme'
import { ElMessage } from 'element-plus'

import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
const router = useRouter()
import { WebsocketStore } from '@/components/websocket'
const Websocket = WebsocketStore()
import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  dialogShow: false,
  query: {
    old_password: '',
    new_password: '',
    username: '',
    google_check: 0, // 是否验证
    google_url: '', // 谷歌二维码
    google_secret: '', // 谷歌二维码
    google_code: '', // 谷歌验证码
  },
  rules: {
    old_password: [{ required: true, message: '请输入', trigger: 'blur' }],
    new_password: [{ required: true, message: '请输入', trigger: 'blur' }],
    google_code: [{ required: false, message: '请输入', trigger: 'blur' }],
  },
})

onMounted(() => {
  if (theme) {
    document.querySelectorAll('html')[0].className = theme
    actColor.value = colors.find((item) => item.name == theme)?.color ?? ''
  }
  // 首次登录必须修改密码 + 绑定谷歌验证码(总代)
  if (indexStore.userInfo.first_login && indexStore.userInfo.is_general_agent) {
    data.dialogShow = true
  }
  data.query.google_code = ''
  data.query.google_check = indexStore.userInfo.google_check
  data.query.google_secret = indexStore.userInfo.google_secret
  data.query.google_url = indexStore.userInfo.google_url

  if(data.query.google_check && !data.query.google_url  && !data.query.google_secret){
    chooseGoogle(1,false)
  }

  Websocket.connectWebSocket()
})

// 多语言切换
const lang = ref(getLang())
const changeLang = (val: string) => {
  locale.value = val
  localStorage.setItem('lang', val)
}

let actColor = ref<string>('')
// 切换主题
const command = (item: any) => {
  actColor.value = item.color
  document.querySelectorAll('html')[0].className = item.name
  localStorage.setItem('theme', item.name)
}
// 修改密码
const addQuery = ref<FormInstance>()
const save = async () => {
  if (!addQuery.value) return
  await addQuery.value.validate(async (valid, fields) => {
    if (valid) {
      let query = JSON.parse(JSON.stringify(data.query));
      if (query.old_password && query.new_password && query.old_password == query.new_password) {
        return ElMessage.error('新密码不能与旧密码一样！')
      }

      if ((indexStore.userInfo.google_check  || query.google_check) && !query.google_code) {
        return ElMessage.error('请输入谷歌验证码')
      } else if (!indexStore.userInfo.google_check && !query.google_check) {
        query.google_url = ''
        query.google_secret = ''
      }
      query.google_code = Number(query.google_code)
      query.username = indexStore.userInfo.username
      await putchangePassword(query)
      data.dialogShow = false
      ElMessage.success('修改成功')
      loginOut()
    }
  })
}

const loginOut = () => {
  // 清除缓存
  localStorage.clear()
  sessionStorage.clear()
  location.reload()
  router.replace('login')
  Websocket.handleSocketClose()
}

// 是否开启谷歌验证码
const chooseGoogle = async (value: number,show:boolean) => {
  if(indexStore.userInfo.google_url && indexStore.userInfo.google_check ||  data.query.google_check){
    data.rules.google_code[0].required = true
  }else{
    data.rules.google_code[0].required = false
  }
  if (value) {
    if (data.query.google_url && !show) return
    let res = await googleKey({ username: indexStore.userInfo.username })
    data.query.google_url = res.data.google_url
    data.query.google_secret = res.data.google_secret
  }else{
    if (indexStore.userInfo.first_login && indexStore.userInfo.is_general_agent) {
      indexStore.userInfo.google_check = 0
    }
  }
}

// 更换谷歌验证码
const changeGoogle = async () => {
  if (!data.query.google_code) {
    return ElMessage.error('请输入谷歌验证码')
  }
  await checkGoogleKey({
    google_code: data.query.google_code,
    google_secret: data.query.google_secret
  })
  chooseGoogle(1,true)
}

const width = ref('260px')
const collapse = (val: string) => {
  if (val) {
    width.value = '64px'
  } else {
    width.value = '260px'
  }
}
</script>
<style lang="scss">
.app {
  background: var(--homeback);
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
}

.el-aside {
  background: var(--asideBg);
  background-size: cover;
  background-position: center;
  height: 100%;
  box-shadow: $boxShadow;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  &::after {
    display: block;
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: var(--menu-shadow);
    opacity: 0.85;
    top: 0;
    left: 0;
    z-index: 1;
  }
}

.el-main {
  margin-left: 20px;
  padding: 0;
}

.main-header {
  display: flex;
  height: 50px;
  margin-bottom: 10px;
}

.main-bread {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
}

.main-user {
  display: flex;
  font-size: 14px;
  padding: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;

  .user-time {
    margin: 3px 10px 0;
  }

  .user-username {
    font-size: 16px;
    display: flex;
    align-items: center;
  }
}

.router-box {
  color: var(--text);
  height: 92vh;
  min-height: 92vh;
  max-height: 92vh;
  overflow-y: auto;
  // height: calc(100% - 60px);
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  font-weight: bold;
}

:deep(.el-dropdown-link) {
  font-weight: bold;
  margin-top: 6px;
  font-size: 14px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.color-box {
  border: 3px solid orange;
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin: -1px 10px 0 0;
}
</style>